package cn.iocoder.yudao.module.hs.job;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.module.hs.netty.Transmission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashSet;

@Component
@Slf4j
public class ChannelExpireJob implements JobHandler {

    @Override
    public String execute(String param) {
        log.info("开始执行设备超时断开任务");
        int count = 0;
        if (CollUtil.isNotEmpty(Transmission.getChannelExpireTimeMap())) {
            // 使用集合副本进行遍历以避免ConcurrentModificationException
            for (String deviceId : new HashSet<>(Transmission.getChannelExpireTimeMap().keySet())) {
                if (Transmission.getChannelExpireTimeMap().containsKey(deviceId)) {
                    LocalDateTime channelExpireTime = Transmission.getChannelExpireTimeMap().get(deviceId);
                    if (channelExpireTime.plusMinutes(2).isBefore(LocalDateTime.now())) {
                        log.info("设备：{}已超时，断开连接，清空缓存", deviceId);
                        Transmission.removeChannel(deviceId);
                    }
                }
            }
        }
        log.info("设备超时断开任务执行完毕，断开 {} 台", count);
        return "执行成功";
    }
}
